package com.xpqh.ksg.interceptor;

import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.common.utils.JwtTokenUtil;
import com.xpqh.ksg.exception.WebApiException;
import common.utils.CommonUtil;
import common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class      NoRepeatSubmitInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		// 获取请求的 URL
		String requestURI = request.getRequestURI();

		// 检查是否是 /save/ 路径
		if (requestURI.contains("/save") || requestURI.contains("/update") || requestURI.contains("/sendsms")) {
			// 从请求头中获取 Token（假设 Token 放在 Authorization 头中）
			String token = request.getHeader("Authorization");

			// 如果 Token 为空，尝试从请求参数中获取
			if (!StringUtils.isNotBlank(token)) {
				return true;
			}

			String userId = jwtTokenUtil.getUsernameFromToken(token.substring(7));

			// 生成唯一标识：Token + URL
			String requestKey = "";

			if (requestURI.contains("/sendsms") || requestURI.contains("/update/register")) {
				String ip = CommonUtil.getIp(request);
				requestKey = "rep_sub:" + ip + ":" + requestURI;
			} else {
				requestKey = "rep_sub:" + userId + ":" + requestURI;
			}

			// 检查 Redis 中是否存在该标识
			if (Boolean.TRUE.equals(redisTemplate.hasKey(requestKey))) {
				throw new WebApiException(BizExceptionEnum.REPEAT_SUBMIT);
			} else {
				// 将标识存储到 Redis，设置过期时间（例如 10 秒）
				redisTemplate.opsForValue().set(requestKey, "submitted", 6, TimeUnit.SECONDS);
			}
		}
		return true;
	}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // do nothing
    }
}
